import QRCode from 'qrcode.react'
import { useEffect, useState } from 'react'
import { useModel } from '@umijs/max'
import './QRCodeBox.less'
import { Result } from 'antd'

const weixin_logo = 'https://qny.weizulin.cn/images/202403201051162.svg'
const zhifubao_logo = 'https://qny.weizulin.cn/images/202403201051163.svg'

const payTypeMap = {
  1: {
    name: '支付宝',
    icon: zhifubao_logo
  },
  2: {
    name: '微信',
    icon: weixin_logo
  }
}

const QRCodeBox = ({ qrData }) => {
  const { pay_type, amount, out_trade_no, qr_code, note, create_time, goods_name } = qrData
  const { GetRiskRechargePayResult } = useModel('RiskRecharge')

  // 0 未支付 1 已支付 2 超时
  const [payStatus, setPayStatus] = useState(0)
  let timer = null

  useEffect(() => {
    getOrderStatus()
    return () => {
      clearTimeout(timer)
    }
  }, [])

  // 获取订单状态
  const getOrderStatus = async () => {
    const orderRes = await GetRiskRechargePayResult({ out_trade_no })
    if (orderRes) {
      if (orderRes.is_pay === 0) {
        timer = setTimeout(() => {
          getOrderStatus()
        }, 3000)
      } else {
        setPayStatus(orderRes.is_pay)
        clearTimeout(timer)
      }

      // 两分钟后没有支付成功的操作
      setTimeout(() => {
        setPayStatus(2)
        clearTimeout(timer)
      }, 120000)
    }
  }

  return (
    <div className='qrcode_box'>
      <div className='qrcode_title'>{payStatus === 0 ? '订单提交成功,请尽快支付' : '充值结果'}</div>

      {payStatus === 0 ? (
        <>
          <div className='qrcode_amount'>¥{amount.toFixed(2)}</div>

          <div className='qrcode_tips'>
            <img src={payTypeMap[Number(pay_type)].icon} alt={payTypeMap[Number(pay_type)].name} />
            <p>打开{payTypeMap[Number(pay_type)].name}扫码支付</p>
          </div>

          <div className='qrcode_code'>
            <QRCode value={qr_code} size={256} fgColor='#000000' />
          </div>

          <div className='qrcode_info'>
            <p>订单编号 : {out_trade_no}</p>
            <p>商品名称 : {goods_name}</p>
            <p>创建时间 : {create_time}</p>
            {note ? <p>备注 : {note}</p> : null}
          </div>
        </>
      ) : (
        <div className='pay_status_info'>
          {payStatus === 1 && <Result status='success' title='支付成功' subTitle={`您的风控充值订单已完成`} />}
          {payStatus === 2 && <Result status='error' title='支付超时' subTitle='二维码超时,请重新进行订单生成' />}
        </div>
      )}
    </div>
  )
}
export default QRCodeBox
